import {
  _decorator,
  CCFloat,
  CCInteger,
  Component,
  instantiate,
  Node,
  Prefab,
  UITransform,
  v3,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("Head")
export class Head extends Component {
  //#region 预制体引用
  @property(Prefab)
  public bodyPrefab: Prefab = null; // 蛇身预制体

  @property(Prefab)
  public foodPrefab: Prefab = null; // 实物预制体
  //#endregion

  //#region 变量
  @property(Array(Node))
  public bodyArray: Node[] = []; // 蛇身体数组（包括蛇头）

  @property(CCInteger)
  bodyNum: number = 2; // 初始蛇身数量

  @property(CCFloat)
  bodyDistance: number = 50; //蛇身之间的距离

  speed: number = 200; // 蛇移动速度
  //#endregion

  protected onLoad(): void {
    this.bodyArray.push(this.node);
    for (let i = 0; i < this.bodyNum; i++) {
      this.getNewBody();
    }
  }

  getNewBody() {
    const newBody = instantiate(this.bodyPrefab);
    if (this.bodyArray.length === 1) {
      const dir = this.node.position.clone().normalize();
      newBody.setPosition(
        this.node.position
          .clone()
          .subtract(dir.multiplyScalar(this.bodyDistance))
      );
    }
    this.node.parent.addChild(newBody);
    this.bodyArray.push(newBody);
  }

  start() {
    this.node.setPosition(this.randomCreateHead());
    this.node.parent.addChild(instantiate(this.foodPrefab));
  }

  update(deltaTime: number) {}

  /**
   * 随机创建蛇头的位置
   */
  randomCreateHead() {
    const offSetDis = 200; // 防止一生成就撞墙
    const width = this.node.parent.getComponent(UITransform).width - offSetDis;
    const height =
      this.node.parent.getComponent(UITransform).height - offSetDis;
    const randomX = Math.round(Math.random() * width - width / 2);
    const randomY = Math.round(Math.random() * height - height / 2);
    return v3(randomX, randomY, 0);
  }
}
